package com.vegetable.modules.service.inbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.modules.entity.inbound.OrderCost;
import com.vegetable.modules.mapper.inbound.OrderCostMapper;
import com.vegetable.modules.service.inbound.IOrderCostService;
import com.vegetable.modules.service.stock.IStockService;
import com.vegetable.modules.entity.stock.Stock;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 入库订单费用表 服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-07
 */
@Slf4j
@Service
@AllArgsConstructor
public class OrderCostServiceImpl extends ServiceImpl<OrderCostMapper, OrderCost> implements IOrderCostService {

    @Lazy
    @Autowired
    private IStockService stockService;

    @Override
    public List<OrderCost> selectByMainId(Long mainId) {
        log.info("开始根据mainId查询订单费用，mainId: {}", mainId);
        QueryWrapper<OrderCost> orderCostQueryWrapper = new QueryWrapper();
        orderCostQueryWrapper.eq("main_id", mainId);
        List<OrderCost> orderCosts = this.getBaseMapper().selectList(orderCostQueryWrapper);
        log.info("根据mainId {} 查询到 {} 条订单费用记录", mainId, orderCosts != null ? orderCosts.size() : 0);
        
        // 记录每条订单费用的详细信息
        if (orderCosts != null) {
            for (OrderCost cost : orderCosts) {
                log.debug("订单费用记录 - ID: {}, 费用名称: {}, 金额: {}, mainId: {}", 
                    cost.getId(), cost.getCostClauseName(), cost.getMoney(), cost.getMainId());
            }
        }
        
        return orderCosts;
    }

    @Override
    public List<OrderCost> selectByMainIds(List<Long> mainIds) {
        if (CollectionUtils.isEmpty(mainIds)) {
            return new ArrayList<>();
        }
        log.info("批量查询订单费用，订单数量: {}", mainIds.size());
        QueryWrapper<OrderCost> query = new QueryWrapper<>();
        query.in("main_id", mainIds);
        List<OrderCost> orderCosts = this.getBaseMapper().selectList(query);
        log.info("批量查询到 {} 条订单费用记录", orderCosts != null ? orderCosts.size() : 0);
        return orderCosts;
    }

    @Override
    public void deleteByMainId(Long mainId) {
        QueryWrapper<OrderCost> wrapper = new QueryWrapper();
        wrapper.eq("main_id", mainId);
        baseMapper.delete(wrapper);
    }

    @Override
    public boolean save(OrderCost entity) {
        boolean result = super.save(entity);
        if (result) {
            // 订单费用保存成功后，调整相关库存成本
            adjustRelatedStockCosts(entity);
        }
        return result;
    }

    @Override
    public boolean updateById(OrderCost entity) {
        boolean result = super.updateById(entity);
        if (result) {
            // 订单费用更新成功后，调整相关库存成本
            adjustRelatedStockCosts(entity);
        }
        return result;
    }

    @Override
    public boolean removeById(Serializable id) {
        // 在删除前先获取完整的订单费用信息
        OrderCost orderCost = this.getById(id);
        boolean result = super.removeById(id);
        if (result && orderCost != null) {
            // 订单费用删除成功后，调整相关库存成本
            adjustRelatedStockCosts(orderCost);
        }
        return result;
    }

    /**
     * 调整相关库存成本
     * @param orderCost 订单费用
     */
    private void adjustRelatedStockCosts(OrderCost orderCost) {
        try {
            log.info("开始调整订单费用相关的库存成本，订单费用ID: {}, 费用名称: {}, 金额: {}", 
                orderCost.getId(), orderCost.getCostClauseName(), orderCost.getMoney());
            
            // 根据mainId查找关联的库存记录
            List<Stock> relatedStocks = stockService.queryStockByOrderId(orderCost.getMainId());
            if (relatedStocks != null && !relatedStocks.isEmpty()) {
                log.info("找到 {} 条关联的库存记录", relatedStocks.size());
                
                for (Stock stock : relatedStocks) {
                    log.info("监控订单费用变化，库存ID: {}, 商品名称: {}, 当前成本单价: {}", 
                        stock.getId(), stock.getCommodityName(), stock.getCostWeight());
                }
            } else {
                log.info("未找到与订单费用关联的库存记录，订单费用ID: {}", orderCost.getId());
            }
        } catch (Exception e) {
            log.error("调整相关库存成本时发生错误，订单费用ID: {}", orderCost.getId(), e);
        }
    }
}
